package com.hc.adapter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.hc.DTO.AnimalDTO;
import com.hc.appanimal.R;
import com.hc.constants.Constants;
import com.hc.ultil.PicassoUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class AnimalAdapter extends ArrayAdapter<Object> {
	Context mContext;
	private ArrayList<Object> arrObject;
	DisplayImageOptions options;

	public AnimalAdapter(Context context, int resource, ArrayList<Object> arr) {
		super(context, resource, arr);
		mContext = context;
		arrObject = arr;
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.ic_empty)
				.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
	}

	class viewHolder {
		ImageView imageAnimal;
		TextView txtNamAnimal;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return arrObject.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return arrObject.get(position);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View rowView = null;
		if(convertView == null){
			rowView = inflater.inflate(R.layout.grid_row, parent, false);
		}else{
			rowView = convertView;
		}
		

		viewHolder holder = new viewHolder();

		// holder.icon = (ImageView) rowView.findViewById(R.id.icon);
		// holder.txtImageName = (TextView)
		// rowView.findViewById(R.id.txtImageName);
		holder.imageAnimal = (ImageView) rowView.findViewById(R.id.imageAnimal);
		holder.txtNamAnimal = (TextView) rowView
				.findViewById(R.id.txtNamAnimal);
		holder.txtNamAnimal.setTextSize(15.0f);
		try {
			AnimalDTO dto = (AnimalDTO) arrObject.get(position);
			holder.txtNamAnimal.setText(dto.getCommonName());

			String path = dto.getAnimalImagesDTO().getImageUrl();
			path = path.replaceAll(" ", "%20");
			if (path != null) {
				String[] strs = path.split("/");
				File f = new File(Environment.getExternalStorageDirectory()
						+ "/" + Constants.APP_NAME + "/" + strs[4] + "/"
						+ strs[5]);
				
				String pathImg = "file://"+ f.getAbsolutePath();

				if (f.exists()) {

					ImageLoader.getInstance().displayImage(pathImg,
							holder.imageAnimal, options,
							new SimpleImageLoadingListener() {
								@Override
								public void onLoadingStarted(String imageUri,
										View view) {

								}

								@Override
								public void onLoadingFailed(String imageUri,
										View view, FailReason failReason) {

								}

								@Override
								public void onLoadingComplete(String imageUri,
										View view, Bitmap loadedImage) {

								}
							}, new ImageLoadingProgressListener() {
								@Override
								public void onProgressUpdate(String imageUri,
										View view, int current, int total) {

								}
							});
					// Bitmap bmp = decodeFile(f.getAbsolutePath(), imageWidth,
					// imageWidth);
					// holder.imageAnimal.setImageBitmap(bmp);
				} else {
					PicassoUtils.getInstance().showImageFromUrl(mContext, path,
							R.drawable.spin_animation, holder.imageAnimal);
					// TODO: create folder?

					PicassoUtils.getInstance().saveImageFromUrl(
							mContext.getApplicationContext(), path, strs[5],
							strs[4]);
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
		}

		return rowView;
	}

	public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
		try {

			File f = new File(filePath);

			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			final int REQUIRED_WIDTH = WIDTH;
			final int REQUIRED_HIGHT = HIGHT;
			int scale = 1;
			while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
					&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
				scale *= 2;

			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

}
